import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
import '../../base/MyScaffold.dart';
import '../../res.dart';
import '../loginregister/Login.dart';
import '../../utils/Toast/MyTosat.dart';
import '../../utils/color/ColorUtils.dart';
import '../../widgets/MyLocalImage.dart';
import '../../widgets/TextView.dart';
import 'package:get/get.dart';
import 'package:in_app_purchase/in_app_purchase.dart';
import 'package:in_app_purchase_android/billing_client_wrappers.dart';
import 'package:in_app_purchase_android/in_app_purchase_android.dart';
import 'package:in_app_purchase_storekit/in_app_purchase_storekit.dart';

import '../../api/ApiUtils.dart';
import '../../api/request/VipRequest.dart';
import '../../utils/userbloc/user_bloc.dart';

class Subscribe extends StatefulWidget {
  const Subscribe({Key? key}) : super(key: key);

  @override
  State<Subscribe> createState() => _SubscribeState();
}

class _SubscribeState extends State<Subscribe> {
// 产品
  List<ProductDetails> products = <ProductDetails>[];
  final InAppPurchase _inAppPurchase = InAppPurchase.instance;

// 购买
  late StreamSubscription<List<PurchaseDetails>> _purchaseSubscription;

  var year = "";
  var year_Price;

  var month = "";
  var month_Price;

  int save = 0;
  bool postion = true;

  @override
  void initState() {
    _purchaseSubscription =
        _inAppPurchase.purchaseStream.listen((purchaseDetailsList) {
      for (final purchaseDetails in purchaseDetailsList) {
        _listenToPurchaseUpdated(purchaseDetails);
      }
    }, onDone: () {
      _purchaseSubscription.cancel();
    });

    /// 处理未完成的订单
    //_handlePastPurchases();
    // apiShow(
    //     api: api_vip_rules(device: 1),
    //     success: (result) {
    //       print(result.data);
    //     },
    //     failure: (e) {
    //       print(e);
    //     });
    getDiscounts();
    super.initState();
  }

  getDiscounts() async {
    await getYear("com_pdfeditor_yearly_subscription");

    await getMonth("com_pdfeditor_monthly_subscription");

    var Y = year_Price / (month_Price * 12);
    save = (Y * 100).toInt();
    print(save);
    setState(() {});
  }

  @override
  void dispose() {
    // TODO: implement dispose
    _purchaseSubscription.cancel();
    super.dispose();
  }

  /// 处理未完成订单
  Future<void> _handlePastPurchases() async {
    /// 如果是Android系统
    if (Platform.isAndroid) {
      /// 查询未处理的订单
      final androidPlatformAddition = _inAppPurchase
          .getPlatformAddition<InAppPurchaseAndroidPlatformAddition>();
      final response = await androidPlatformAddition.queryPastPurchases();
      if (response.error == null) {
        final purchaseDetailsList = response.pastPurchases;
        for (final purchaseDetails in purchaseDetailsList) {
          if (purchaseDetails.billingClientPurchase.purchaseState ==
              PurchaseStateWrapper.pending) {
            /// 订单未付款，此时需要提醒用户完成购买，否则无法进行下一笔订单
            _handleGooglePendingPurchase(purchaseDetails);
          } else if (purchaseDetails.billingClientPurchase.purchaseState ==
              PurchaseStateWrapper.purchased) {
            /// 订单已付款，向服务器验证订单票据
            await _verifyPurchase(purchaseDetails);
          }
        }
      }
    }
  }

  Future<void> getYear(String productId) async {
    final response =
        await InAppPurchase.instance.queryProductDetails({productId});
    var productDetail = response.productDetails[1];
    year = productDetail.price;
    year_Price = productDetail.rawPrice;
    setState(() {});
  }

  Future<void> getMonth(String productId) async {
    final response =
        await InAppPurchase.instance.queryProductDetails({productId});
    var productDetail = response.productDetails[0];
    month = productDetail.price;
    month_Price = productDetail.rawPrice;
    setState(() {});
  }

  /// 发起支付请求
  /// @productId: 产品ID
  /// @existedOrderNo：自己服务器产生的订单号，若有值则不重新创建订单，可用于补单时
  /// @pointId: 选择的点数套餐，创建订单时必传
  static Future<void> startPay(
      {required String productId, String? existedOrderNo, int? pointId}) async {
    MyToast().show("正在创建订单");

    /// 检测内购是否可用
    final available = await InAppPurchase.instance.isAvailable();
    if (!available) {
      MyToast().show("不支持内购功能");
      return;
    }

    /// 查询产品id是否在服务器上注册了
    final response =
        await InAppPurchase.instance.queryProductDetails({productId});

    if (response.error != null) {
      MyToast().show(response.error!.message);
      return;
    }

    /// 未查询到产品
    if (response.productDetails.isEmpty) {
      return;
    }

    /// 創建訂單
    var orderNo = existedOrderNo;
    String? orderUuidNo;
    if (orderNo == null) {
      // final orderModel = await PurchaseApi.createOrder(pointId: pointId);
      // orderNo = orderModel.number;
      // orderUuidNo = orderModel.uuidNumber;
    }

    final purchaseParam = PurchaseParam(
      productDetails: response.productDetails.first,

      /// 注意：iOS的applicationUserName必须为uuid格式，否则App Store服务器不会保存
      /// android: 自己服務器上生成的訂單號
      /// iOS: 自己服务器上生成的与订单绑定的uuid字符串
      applicationUserName: Platform.isIOS ? orderUuidNo : orderNo,
    );

    /// 发起支付请求
    try {
      await InAppPurchase.instance.buyConsumable(
        purchaseParam: purchaseParam,

        /// 安卓不自动消耗，会在后台服务器进行消耗
        autoConsume: !Platform.isAndroid,
      );
    } catch (e) {
      print("=====${e.toString()}");
    }
  }

  /// 处理Google的PENDING待处理购买交易
  void _handleGooglePendingPurchase(GooglePlayPurchaseDetails purchaseDetails) {
    final productId = purchaseDetails.productID;
    final orderNo = purchaseDetails.billingClientPurchase.obfuscatedAccountId;
    // MyMessageDialog(
    //   width: 305.wRate,
    //   icon: 'dialog/publish',
    //   title: '未完成訂單',
    //   message: '檢測到您有未完成訂單，是否繼續？',
    //   onConfirm: () {
    //     startPay(productId: productId, existedOrderNo: orderNo);
    //   },
    // ).show(context);
    MyToast().show("檢測到您有未完成訂單，是否繼續？");
  }

  /// 监听内购更新
  Future<void> _listenToPurchaseUpdated(PurchaseDetails purchaseDetails) async {
    if (purchaseDetails.status == PurchaseStatus.pending) {
      /// 等待购买中
      print('等待购买中');

      /// iOS系统此时正处于拉起支付状态，需要比较长的时间，此处给一个提示
      /// Android系统此时正处于支付操作完成，等待Google批准状态
      if (Platform.isIOS) {
        //YZToastUtil.showLoading(message: '正在拉起支付');
      }
    } else {
      if (Platform.isIOS) {
        //YZToastUtil.dismiss();
      }
      if (purchaseDetails.status == PurchaseStatus.error) {
        /// 购买出错，提示错误信息
        print('购买出错：${purchaseDetails.error?.message}');
        final error = purchaseDetails.error;
        if (error != null) {
          // YZToastUtil.showMessage(error.message);
        }
        _completeApplePurchase(purchaseDetails);
      } else if (purchaseDetails.status == PurchaseStatus.canceled) {
        /// 购买取消
        print('购买取消');
        _completeApplePurchase(purchaseDetails);
      } else if (purchaseDetails.status == PurchaseStatus.purchased ||
          purchaseDetails.status == PurchaseStatus.restored) {
        /// 购买成功或恢复购买，向服务器验证订单票据
        print('购买成功或恢复购买:${purchaseDetails.status}');
        await _verifyPurchase(purchaseDetails);
      }
    }
  }

  /// 将Apple订单标记为已完成
  void _completeApplePurchase(PurchaseDetails purchaseDetails) {
    /// 只需要iOS，Android会在后台进行消耗或确认操作
    if (purchaseDetails is AppStorePurchaseDetails) {
      if (purchaseDetails.pendingCompletePurchase) {
        _inAppPurchase.completePurchase(purchaseDetails);
      }
    }
  }

  Future<void> _verifyPurchase(PurchaseDetails purchaseDetails) async {
    // YZToastUtil.showLoading(message: '正在驗證訂單');

    if (purchaseDetails is AppStorePurchaseDetails) {
      /// 向服务器验证票据
      final params = <String, dynamic>{
        'transaction_id':
            purchaseDetails.skPaymentTransaction.transactionIdentifier,
      };
    } else if (purchaseDetails is GooglePlayPurchaseDetails) {
      /// 向服务器验证票据
      final params = <String, dynamic>{
        'packageName': "com.pdfeditor.apps",
        'productId': purchaseDetails.productID,
        'purchaseToken': purchaseDetails.billingClientPurchase.purchaseToken,
        'order_no': purchaseDetails.billingClientPurchase.obfuscatedAccountId,
      };
      print("向服务器验证票据$params");
      apiShow(
          api: googlePay(params),
          success: (result) {
            print(result.data);
          },
          failure: (e) {
            print(e);
          });
    }
  }

  @override
  Widget build(BuildContext context) {
    return MyScaffold(
      navBarHide: true,
      body: Container(
        child: Column(
          children: [
            Stack(
              children: [
                const MyLocalImage(
                  Res.ubscriptions_img_bg,
                  height: 190,
                ),
                Positioned(
                  top: 16,
                  left: 16,
                  child: MyLocalImage(
                    Res.sys_icon_delete_grey3x,
                    width: 24,
                    height: 24,
                    onclick: () {
                      Get.back();
                    },
                  ),
                )
              ],
            ),
            TextView(
              "feature".tr,
              style: TextStyle(
                  color: ColorUtils.text,
                  fontSize: 24,
                  fontWeight: FontWeight.bold),
              margin: const EdgeInsets.only(top: 16),
            ),
            Item("unlimited".tr),
            Item("conversion".tr),
            Item("merge".tr),
            Item("unlock".tr),
            Item("ads".tr),
            Expanded(
                child: Column(
              children: [
                // Container(
                //   alignment: Alignment.center,
                //   height: 98,
                //   margin:
                //       const EdgeInsets.symmetric(vertical: 10, horizontal: 16),
                //   decoration: BoxDecoration(
                //       borderRadius: BorderRadius.circular(6),
                //       gradient: LinearGradient(
                //           colors: postion
                //               ? [rgba(129, 8, 255, 1), rgba(245, 98, 183, 1)]
                //               : [
                //                   rgba(151, 151, 151, 1),
                //                   rgba(151, 151, 151, 1)
                //                 ])),
                //   child: Container(
                //       alignment: Alignment.center,
                //       decoration: BoxDecoration(
                //           borderRadius: BorderRadius.circular(6),
                //           gradient: LinearGradient(colors: [
                //             rgba(129, 8, 255, 1),
                //             rgba(245, 98, 183, 1)
                //           ])),
                //       child: Container(
                //         child: Column(
                //           children: [
                //             TextView(
                //               "BEST VALUE：SAVE ${100 - save}%",
                //               margin: const EdgeInsets.symmetric(vertical: 6),
                //               style: const TextStyle(color: Colors.white),
                //             ),
                //             Expanded(
                //               child: Container(
                //                 alignment: Alignment.center,
                //                 margin: EdgeInsets.all(postion ? 2.5 : 1),
                //                 decoration: BoxDecoration(
                //                     color: postion
                //                         ? rgba(251, 247, 255, 1)
                //                         : Colors.white,
                //                     borderRadius: const BorderRadius.only(
                //                         bottomLeft: Radius.circular(5),
                //                         bottomRight: Radius.circular(5))),
                //                 child: Column(
                //                   mainAxisAlignment: MainAxisAlignment.center,
                //                   children: [
                //                     TextView(
                //                       "star 3-day Free Tria",
                //                       style: TextStyle(
                //                           color: ColorUtils.text, fontSize: 20),
                //                     ),
                //                     TextView(
                //                       "then  $year  per year",
                //                       margin: const EdgeInsets.only(top: 2),
                //                       style: TextStyle(color: ColorUtils.text_),
                //                     )
                //                   ],
                //                 ),
                //               ),
                //             )
                //           ],
                //         ),
                //       )),
                // ),
                InkWell(
                  onTap: () {
                    postion = true;
                    setState(() {});
                  },
                  child: Container(
                    alignment: Alignment.center,
                    height: 98,
                    margin: const EdgeInsets.symmetric(
                        vertical: 10, horizontal: 16),
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(6),
                        gradient: LinearGradient(
                            colors: postion
                                ? [rgba(129, 8, 255, 1), rgba(245, 98, 183, 1)]
                                : [
                                    rgba(151, 151, 151, 1),
                                    rgba(151, 151, 151, 1)
                                  ])),
                    child: Column(
                      children: [
                        Container(
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                              borderRadius: const BorderRadius.vertical(
                                  top: Radius.circular(5)),
                              gradient: LinearGradient(colors: [
                                rgba(129, 8, 255, 1),
                                rgba(245, 98, 183, 1)
                              ])),
                          child: TextView(
                            "BEST VALUE：SAVE ${100 - save}%",
                            margin: const EdgeInsets.symmetric(vertical: 6),
                            style: const TextStyle(color: Colors.white),
                          ),
                        ),
                        Expanded(
                          child: Container(
                            alignment: Alignment.center,
                            margin: EdgeInsets.all(postion ? 2.5 : 1),
                            decoration: BoxDecoration(
                                color: postion
                                    ? rgba(251, 247, 255, 1)
                                    : Colors.white,
                                borderRadius: const BorderRadius.only(
                                    bottomLeft: Radius.circular(5),
                                    bottomRight: Radius.circular(5))),
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                TextView(
                                  "free_trial".tr,
                                  style: TextStyle(
                                      color: ColorUtils.text, fontSize: 20),
                                ),
                                TextView(
                                  "$year ${"per_year".tr}",
                                  margin: const EdgeInsets.only(top: 2),
                                  style: TextStyle(color: ColorUtils.text_),
                                )
                              ],
                            ),
                          ),
                        )
                      ],
                    ),
                  ),
                ),
                InkWell(
                  onTap: () {
                    postion = false;
                    setState(() {});
                  },
                  child: Container(
                    alignment: Alignment.center,
                    margin: const EdgeInsets.symmetric(
                        vertical: 10, horizontal: 16),
                    height: 66,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(5),
                      gradient: LinearGradient(
                          colors: !postion
                              ? [rgba(129, 8, 255, 1), rgba(245, 98, 183, 1)]
                              : [
                                  rgba(151, 151, 151, 1),
                                  rgba(151, 151, 151, 1)
                                ]),
                    ),
                    child: Container(
                      alignment: Alignment.center,
                      margin: EdgeInsets.all(!postion ? 2.5 : 1),
                      decoration: BoxDecoration(
                          color: !postion
                              ? rgba(251, 247, 255, 1)
                              : rgba(255, 255, 255, 1),
                          borderRadius: BorderRadius.circular(5)),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          TextView(
                            "start_now".tr,
                            style:
                                TextStyle(color: ColorUtils.text, fontSize: 20),
                          ),
                          TextView(
                            "${month}${"per_month".tr}",
                            margin: const EdgeInsets.only(top: 2),
                            style: TextStyle(color: ColorUtils.text_),
                          )
                        ],
                      ),
                    ),
                  ),
                )
              ],
            )),
            Container(
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(6),
                  gradient: LinearGradient(
                      colors: [rgba(129, 8, 255, 1), rgba(245, 98, 183, 1)])),
              margin: const EdgeInsets.symmetric(vertical: 10, horizontal: 16),
              child: TextView(
                "continues".tr,
                height: 50,
                alignment: Alignment.center,
                style: const TextStyle(
                    color: Colors.white,
                    fontSize: 16,
                    fontWeight: FontWeight.bold),
                onclick: () {
                  if (UserBlocTool.isLogin()) {
                    if (postion) {
                      startPay(productId: "com_pdfeditor_yearly_subscription");
                    } else {
                      startPay(productId: "com_pdfeditor_monthly_subscription");
                    }
                  } else {
                    tips();
                  }
                },
              ),
            )
          ],
        ),
      ),
    );
  }

  tips() {
    Get.defaultDialog(
      radius: 10,
      contentPadding: EdgeInsets.zero,
      content: TextView(
        "noLogin".tr,
        maxLines: 2,
        textAlign: TextAlign.center,
        style: TextStyle(
            color: ColorUtils.text, fontSize: 16, fontWeight: FontWeight.bold),
        margin: const EdgeInsets.symmetric(horizontal: 32, vertical: 16),
      ),
      actions: [
        Column(
          children: [
            const Divider(
              height: 1,
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                TextView(
                  "cancel".tr,
                  style: const TextStyle(
                      fontWeight: FontWeight.bold,
                      color: Colors.black,
                      fontSize: 16),
                  backcolor: rgba(247, 247, 247, 1),
                  textAlign: TextAlign.center,
                  radius: BorderRadius.circular(6),
                  padding: const EdgeInsets.symmetric(vertical: 11),
                  width: 140,
                  margin: const EdgeInsets.symmetric(vertical: 16),
                ),
                const SizedBox(
                  width: 16,
                ),
                TextView(
                  "ok".tr,
                  style: const TextStyle(
                      fontWeight: FontWeight.bold,
                      color: Colors.white,
                      fontSize: 16),
                  backcolor: rgba(255, 78, 77, 1),
                  textAlign: TextAlign.center,
                  radius: BorderRadius.circular(6),
                  padding: const EdgeInsets.symmetric(vertical: 11),
                  width: 140,
                  margin: const EdgeInsets.symmetric(vertical: 16),
                  onclick: () {
                    Get.back();
                    Get.to(const Login());
                  },
                ),
              ],
            ),
          ],
        )
      ],
    );
  }

  Widget Item(String name) {
    return Container(
      height: 24,
      alignment: Alignment.center,
      margin: const EdgeInsets.symmetric(vertical: 12, horizontal: 16),
      child: Row(children: [
        const MyLocalImage(
          Res.list_icon_select_check,
          width: 24,
          height: 24,
        ),
        TextView(
          name,
          style: TextStyle(
              color: ColorUtils.text,
              fontSize: 16,
              fontWeight: FontWeight.bold),
          margin: const EdgeInsets.only(left: 16),
        )
      ]),
    );
  }
}
